package com.wframe.project.jnd.wx.wxImpl;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import org.apache.log4j.Logger;

import com.frame.database.JdataBean;
import com.frame.util.EncryptUtil;

public class WeixSign {

	
	 public static JdataBean sign(String jsapi_ticket, String url) {
		 	JdataBean ret = new JdataBean();
	        String nonce_str = create_nonce_str();
	        String timestamp = create_timestamp();
	        String string1;
	        String signature = "";

	        //注意这里参数名必须全部小写，且必须有序
	        string1 = "jsapi_ticket=" + jsapi_ticket +
	                  "&noncestr=" + nonce_str +
	                  "&timestamp=" + timestamp +
	                  "&url=" + url;

	        try
	        {
	            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
	            crypt.reset();
	            crypt.update(string1.getBytes("UTF-8"));
	            signature = byteToHex(crypt.digest());
	        }
	        catch (NoSuchAlgorithmException e)
	        {
	            e.printStackTrace();
	        }
	        catch (UnsupportedEncodingException e)
	        {
	            e.printStackTrace();
	        }

	        ret.put("url", url);
	        ret.put("jsapi_ticket", jsapi_ticket);
	        ret.put("noncestr", nonce_str);
	        ret.put("timestamp", timestamp);
	        ret.put("signature", signature);

	        return ret;
	    }
	 
	 public static String paysign(Map parms) {
		 	StringBuffer sb=new StringBuffer();
		 	List<String> keys=new ArrayList<String>();
		 	Object[] objs=parms.keySet().toArray();
		 	for(Object obj:objs)
		 		keys.add(obj.toString());
		 	Collections.sort(keys,String.CASE_INSENSITIVE_ORDER);
		 	
		 	Iterator it=parms.entrySet().iterator();
		 	for(String key:keys){
		 		Object v=parms.get(key);
		 		if(v!=null && !"".equals(v.toString()))
		 			sb.append(key+"="+v.toString()+"&");
		 	}
		 	sb.append("key="+WeixAccountConfig.getConfig().getPayKey());
		 	String sign=MD5Util.MD5Encode(sb.toString(), "utf-8").toUpperCase();
	        return sign;
	    }

	    private static String byteToHex(final byte[] hash) {
	        Formatter formatter = new Formatter();
	        for (byte b : hash)
	        {
	            formatter.format("%02x", b);
	        }
	        String result = formatter.toString();
	        formatter.close();
	        return result;
	    }
	    
	public static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

	 public static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
